package com.lzy.crm.wechat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.RedisHelper;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.PpSystemStatusInfo;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.proto.Group.CommMsg;
import com.lzy.crm.proto.RedisData.PlayerInfo;
import com.lzy.crm.service.CreateRoomInfoService;
import com.lzy.crm.service.PpSystemStatusInfoService;
import com.lzy.crm.service.PpUserService;
import com.lzy.crm.wechat.consts.GmConstants;
import com.lzy.crm.wechat.consts.WechatPayProperties;
import com.lzy.crm.wechat.util.WeixinUtil;

/**
 * 游戏登录服务器
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/gm")
public class GmUserController {

	Logger logger = Logger.getLogger(GmUserController.class);

	@Resource
	private PpUserService pUserService;

	@Resource
	private CreateRoomInfoService createRoomInfoService;

	@Resource
	private PpSystemStatusInfoService pSystemStatusInfoService;

	@RequestMapping(path = "/login", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String loginGame(HttpServletRequest request, ModelMap model) {
		String code = request.getParameter("code");
		JsonObject json = new JsonObject();

		if (StringUtil.isEmpty(code)) {
			json.addProperty("err", "code is null");
			return json.toString();
		}

		// 用户信息为空 创建用户信息
		String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code"
				.replace("APPID", WechatPayProperties.getOpenAppId())
				.replace("APPSECRET", WechatPayProperties.getOpenAppSecret())
				.replace("CODE", code);

		JsonObject getCodeResultJson = WeixinUtil.HttpRequest(requestUrl,
				"GET", null);

		logger.info(getCodeResultJson);

		if (getCodeResultJson.has("errcode")) {
			json.addProperty("errcode", getCodeResultJson.get("errcode")
					.getAsString());
			return json.toString();

		}

		String openid = getCodeResultJson.get("openid").getAsString();// 拿到openid
		String unionid = getCodeResultJson.get("unionid").getAsString();// 拿到unionid
		String access_token = getCodeResultJson.get("access_token")
				.getAsString();

		PpUser user = pUserService.getPpUserByUnionId(unionid);

		if (user == null) {
			// 补全信息 或生成信息
			String unioinidrequestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"
					.replace("OPENID", openid).replace("ACCESS_TOKEN",
							access_token);
			JsonObject userinfoJson = WeixinUtil.HttpRequest(
					unioinidrequestUrl, "GET", null);
			System.out.println("userinfoJson" + userinfoJson);
			String nickname = userinfoJson.get("nickname").getAsString();
			String headimgurl = userinfoJson.get("headimgurl").getAsString();
			String sex = userinfoJson.get("sex").getAsString();
			String province = userinfoJson.get("province").getAsString();
			String city = userinfoJson.get("city").getAsString();

			user = new PpUser();
			user.setUphone(null); // `uphone` ' '
			user.setWechat(null); // `wechat` ' '
			user.setRealname(null); // `realname`
			user.setIdnum(null); // `idnum` '暂缺'
			user.setPwd("e10adc3949ba59abbe56e057f20f883e"); // `pwd`
			user.setHeadImgUrl(headimgurl); // `head_img_url` NOT
			user.setAddress(province + city); // `address`
			user.setRid(5); // `rid` '5'
			user.setFrontUid(null); // `front_uid`
			user.setChiefUid(null); // `chief_uid`
			user.setNickname(nickname); // `nickname`
			user.setRoomcard(5); // `roomcard`
			user.setBubble(0); // `bubble` '0'
			user.setRechargeUid(null); // `recharge_uid` NOT
			user.setFreeze(2); // `freeze`
			user.setCreateTime(new Date()); // `create_time`
			user.setUpperLimit(null); // `upper_limit`
			user.setLowerLimit(null); // `lower_limit`
			user.setSex(Integer.parseInt(sex)); // `sex` NOT
			user.setAccessTime(new Date()); // `access_time`
			user.setUnionid(unionid); // `unionid` ''
			user.setOpenid(openid); // `openid` ''
			user.setToken(access_token); // `token` ''
			user.setRefreshToken(access_token); // `refresh_token`
			user.setMoney(0); // `money` '0'
			user.setUstate(0); // `ustate` '0'
			user.setFlag(0); // `flag` '0'
			user.setBackgold(0.0); // `backgold`
			user.setBackcard(0); // `backcard`
			user.setRoomId(0); // `room_id` '0',
			user.setCode(0); // `code` '0' '推广码',
			user.setUserLevel(9); // `user_level` '9'

			Integer newUid = pUserService.insertSelective(user);
			
			// 更新Redis

			Map<String, String> map = new HashMap<String, String>();
			map.put("unionid", user.getUnionid());
			map.put("openid", user.getOpenid());
			map.put("headimgurl", user.getHeadImgUrl());
			map.put("access_token", user.getToken());
			map.put("name", user.getNickname());
			map.put("province", user.getAddress());
			map.put("country", user.getAddress());
			map.put("cash_num", user.getRoomcard().toString());
			map.put("city", user.getAddress());
			map.put("sex", user.getSex().toString());
			map.put("refresh_token", user.getRefreshToken());

			RedisHelper.hmset("account:" + user.getUid() + ":data", map);
		} else {
			user.setAccessTime(new Date());
			pUserService.updateByPrimaryKeySelective(user);
		}

		

		json.addProperty("pid", user.getUid());
		json.addProperty("key", user.getAccessTime().toString());

		return json.toString();
	}

	@RequestMapping(path = "/guest_login", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String Guestlogin(HttpServletRequest request, ModelMap model) {
		String code = request.getParameter("code");
		JsonObject json = new JsonObject();

		if (StringUtil.isEmpty(code)) {
			json.addProperty("err", "code is null");
			return json.toString();
		}

		PpUser user = pUserService.getPpUserByUnionId(code);

		if (user == null) {
			user = new PpUser();
			user.setUphone(code);
			user.setWechat(code);
			user.setRealname(code);
			user.setIdnum(code);
			user.setPwd(code);
			user.setHeadImgUrl("http://thirdwx.qlogo.cn/mmopen/vi_32/oA8yhGYuVMBurqC5ZI1MLhM4bg4LuVJbWicUGe24zXmXDdPiacFdR7yulKKf9n6NeswC326Oz4iaw6xw37PzhibFicQ/132");
			user.setAddress(code);
			user.setRid(5);
			user.setFrontUid(null);
			user.setChiefUid(null);
			user.setNickname(code);
			user.setRoomcard(5);
			user.setBubble(0);
			user.setRechargeUid(null);
			user.setFreeze(2);
			user.setCreateTime(new Date());
			user.setUpperLimit(null);
			user.setLowerLimit(null);
			user.setSex(0);
			user.setAccessTime(new Date());
			user.setUnionid(code);
			user.setOpenid(code);
			user.setToken(code);
			user.setRefreshToken(code);
			user.setMoney(0);
			user.setUstate(0);
			user.setFlag(0);
			user.setBackgold(0.0);
			user.setBackcard(0);
			user.setRoomId(0);
			user.setCode(0);
			user.setUserLevel(9);
			Integer newUid = pUserService.insertSelective(user);
			
			
			// 更新Redis

			Map<String, String> map = new HashMap<String, String>();
			map.put("unionid", user.getUnionid());
			map.put("openid", user.getOpenid());
			map.put("headimgurl", user.getHeadImgUrl());
			map.put("access_token", user.getToken());
			map.put("name", user.getNickname());
			map.put("province", user.getAddress());
			map.put("country", user.getAddress());
			map.put("cash_num", user.getRoomcard().toString());
			map.put("city", user.getAddress());
			map.put("sex", user.getSex().toString());
			map.put("refresh_token", user.getRefreshToken());

			RedisHelper.hmset("account:" + user.getUid() + ":data", map);
		}

		

		json.addProperty("pid", user.getUid());
		json.addProperty("key", user.getAccessTime().toString());

		return json.toString();
	}

	/**
	 * 获取更新
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path = "/GetUpdateConfig", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String GetUpdateConfig(HttpServletRequest request, ModelMap model) {
		// 获取下载地址
		if (StringUtil.isEmpty(GmConstants.files)) {
			PpSystemStatusInfo pSystemStatusInfo = pSystemStatusInfoService
					.getById("download_address");
			GmConstants.files = pSystemStatusInfo.getStatusTip();
		}
		Map<String, String> fileMap = new HashMap<String, String>();
		fileMap.put("android", GmConstants.files);
		fileMap.put("ios", GmConstants.files);
		fileMap.put("files", GmConstants.files);
		return JsonUtil.toJson(fileMap);
	}

	@RequestMapping(path = "/user_info", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public byte[] user_info(HttpServletRequest request, ModelMap model) {
		String uid = request.getParameter("uid");
		if (StringUtil.isEmpty(uid)) {
			// 返回错误回去
			return null;
		}
		com.lzy.crm.proto.RedisData.PlayerInfo.Builder serverPlayerInfo = PlayerInfo
				.newBuilder();

		try {
			PpUser user = pUserService.getPpUser(uid);

			if (user != null) {
				PpSystemStatusInfo pSystemStatusInfo = pSystemStatusInfoService
						.getById("server_notice");

				// serverPlayerInfo.setBajuNum(user)
				// serverPlayerInfo.setBubbleNum(value)
				serverPlayerInfo.setCardNum(user.getRoomcard());
				// serverPlayerInfo.setField(field, value)
				serverPlayerInfo
						.setPaoma(pSystemStatusInfo == null ? "好友同桌，拒绝外挂~"
								: pSystemStatusInfo.getStatusString());
				// serverPlayerInfo.setPaomaBytes(value)

			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(uid);
			logger.error("获取用户信息失败-------" + uid);
		}

		com.lzy.crm.proto.Group.CommMsg.Builder commMsg = CommMsg.newBuilder();
		commMsg.setCode(1);
		commMsg.setResp(serverPlayerInfo.build().toByteString());
		commMsg.setMsg(serverPlayerInfo.build().toString());
		return commMsg.build().toByteArray();
	}

	/**
	 * 通过uid给用户绑定邀请码
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path = "/update_code_uid", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public byte[] updateCodeByUid(HttpServletRequest request, ModelMap model) {
		String uid = request.getParameter("uid");
		String code = request.getParameter("code");

		if (StringUtil.isEmpty(uid) && StringUtil.isEmpty(code)) {
			return null;
		}

		try {
			PpUser ppUser = pUserService.getPpUser(uid);
			int codes = Integer.parseInt(code);
			ppUser.setCode(codes);
			pUserService.updateByPrimaryKeySelective(ppUser);

		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(code);
			logger.error("获取邀请码失败！-----" + code);
		}

		com.lzy.crm.proto.Group.CommMsg.Builder commMsg = CommMsg.newBuilder();
		commMsg.setCode(1);
		return commMsg.build().toByteArray();
	}

	public static void main(String[] args) {

		// 用户信息为空 创建用户信息
		JsonObject userinfoJson = WeixinUtil.HttpRequest(
				"https://ssgw.updrips.com/resource/user/getUserInfo", "POST",
				"access_token=c9cece85f8207aa37e959c1ab6c61b24");

		if (userinfoJson.has("err_code")
				&& !userinfoJson.get("err_code").getAsString().equals("0")) {
			return;
		}
		System.out.println("xianliao-userinfoJson" + userinfoJson);
	}

	@RequestMapping(path = "/login_xianliao", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String loginXianLiao(HttpServletRequest request, ModelMap model) {
		String code = request.getParameter("code");
		JsonObject json = new JsonObject();

		if (StringUtil.isEmpty(code)) {
			json.addProperty("err", "code is null");
			return json.toString();
		}

		// 用户信息为空 创建用户信息
		String data = "appid=cUgf9DXr1rZXGg7L&appsecret=feaQL8vH8cRGyUmp&grant_type=authorization_code&code="
				+ code;
		JsonObject tokenJson = WeixinUtil.HttpRequest(
				"https://ssgw.updrips.com/oauth2/accessToken", "POST", data);

		logger.info("tokenJson = " + tokenJson);

		if (tokenJson.has("err_code")
				&& !tokenJson.get("err_code").getAsString().equals("0")) {
			json.addProperty("err", tokenJson.get("err_code").getAsString());
			return json.toString();
		}

		JsonObject tokens = tokenJson.getAsJsonObject("data");

		String refresh_token = tokens.get("refresh_token").getAsString();
		String access_token = tokens.get("access_token").getAsString();

		JsonObject userinfoJson = WeixinUtil.HttpRequest(
				"https://ssgw.updrips.com/resource/user/getUserInfo", "POST",
				"access_token=" + access_token);

		logger.info("xianliao-userinfoJson" + userinfoJson);

		if (userinfoJson.has("err_code")
				&& !tokenJson.get("err_code").getAsString().equals("0")) {
			json.addProperty("err", userinfoJson.get("err_code").getAsString());
			return json.toString();
		}

		JsonObject info = userinfoJson.getAsJsonObject("data");

		String openId = info.get("openId").getAsString();
		String nickname = info.get("nickName").getAsString();
		String headimgurl = info.get("originalAvatar").getAsString();
		int gender = info.get("gender").getAsInt();
		
		PpUser user = pUserService.getPpUserByUnionId(openId);

		if (user == null) {

			user = new PpUser();
			user.setUphone(null); // `uphone` ' '
			user.setWechat(null); // `wechat` ' '
			user.setRealname(null); // `realname`
			user.setIdnum(null); // `idnum` '暂缺'
			user.setPwd("e10adc3949ba59abbe56e057f20f883e"); // `pwd`
			user.setHeadImgUrl(headimgurl); // `head_img_url` NOT
			user.setRid(5); // `rid` '5'
			user.setFrontUid(null); // `front_uid`
			user.setChiefUid(null); // `chief_uid`
			user.setNickname(nickname); // `nickname`
			user.setRoomcard(5); // `roomcard`
			user.setBubble(0); // `bubble` '0'
			user.setRechargeUid(null); // `recharge_uid` NOT
			user.setFreeze(2); // `freeze`
			user.setCreateTime(new Date()); // `create_time`
			user.setUpperLimit(null); // `upper_limit`
			user.setLowerLimit(null); // `lower_limit`
			user.setSex(gender); // `sex` NOT
			user.setAccessTime(new Date()); // `access_time`
			user.setUnionid(openId); // `unionid` ''
			user.setOpenid(openId); // `openid` ''
			user.setToken(access_token); // `token` ''
			user.setRefreshToken(refresh_token); // `refresh_token`
			user.setMoney(0); // `money` '0'
			user.setUstate(0); // `ustate` '0'
			user.setFlag(0); // `flag` '0'
			user.setBackgold(0.0); // `backgold`
			user.setBackcard(0); // `backcard`
			user.setRoomId(0); // `room_id` '0',
			user.setCode(0); // `code` '0' '推广码',
			user.setUserLevel(9); // `user_level` '9'

			Integer newUid = pUserService.insertSelective(user);
			
			
			
			// 更新Redis

			Map<String, String> map = new HashMap<String, String>();
			map.put("unionid", user.getUnionid());
			map.put("openid", user.getOpenid());
			map.put("headimgurl", user.getHeadImgUrl());
			map.put("access_token", user.getToken());
			map.put("name", user.getNickname());
			map.put("cash_num", user.getRoomcard().toString());
			map.put("sex", user.getSex().toString());
			map.put("refresh_token", user.getRefreshToken());

			RedisHelper.hmset("account:" + user.getUid() + ":data", map);
		} else {
			user.setAccessTime(new Date());
			pUserService.updateByPrimaryKeySelective(user);
		}

		

		json.addProperty("pid", user.getUid());
		json.addProperty("key", user.getAccessTime().toString());

		return json.toString();
	}
	
	
	
	/**
	 * 通过uid给用户绑定上机信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path = "/update_frontUid", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String updatePUIDByUid(HttpServletRequest request, ModelMap model) {
		String uid = request.getParameter("uid");
		String puid = request.getParameter("puid");
		com.lzy.crm.proto.Group.CommMsg.Builder commMsg = CommMsg.newBuilder();
		if (StringUtil.isEmpty(uid) && StringUtil.isEmpty(puid)) {
			commMsg.setCode(2);
			commMsg.setMsg("绑定信息有误~");
			return JsonUtil.toJson(commMsg);
		}

		try {
			PpUser ppUser = pUserService.getPpUser(uid);
			if(ppUser==null){
				commMsg.setCode(2);
				commMsg.setMsg("用户信息错误~");
				return JsonUtil.toJson(commMsg);
			}
			if(ppUser.getFrontUid()==0){
				PpUser pPpUser = pUserService.getPpUser(puid);
				if(pPpUser==null){
					commMsg.setCode(2);
					commMsg.setMsg("绑定代理用户有误~");
					return JsonUtil.toJson(commMsg);
				}
				int frontUid = Integer.parseInt(puid);
				ppUser.setFrontUid(frontUid);
				pUserService.updateByPrimaryKeySelective(ppUser);
			}else{
				String name="";
				PpUser pppUser = pUserService.getPpUser(ppUser.getFrontUid().toString());
				if(pppUser!=null){
					name =pppUser.getNickname();
				}
				commMsg.setCode(1);
				commMsg.setMsg("你已绑定"+name+"，不能重新绑定。");
				return JsonUtil.toJson(commMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(puid);
			logger.error("获取邀请码失败！-----" + puid);
		}
		
		commMsg.setCode(0);
		commMsg.setMsg("绑定成功");
		return JsonUtil.toJson(commMsg);
	}
	
	@RequestMapping(path = "/get_frontInfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getDailiInfo(HttpServletRequest request, ModelMap model) {
		String uid = request.getParameter("uid");
		Map<String,String> retMap = new HashMap<String, String>(); 
		if (StringUtil.isEmpty(uid) ) {
			retMap.put("code", "2");
			retMap.put("msg","查询用户信息有误~");
			return JsonUtil.toJson(retMap);
		}

		try {
			PpUser ppUser = pUserService.getPpUser(uid);
			if(ppUser != null){
				if(ppUser.getFrontUid()!=0){
					PpUser pppUser = pUserService.getPpUser(ppUser.getFrontUid()+"");
					retMap.put("code", "0");
					retMap.put("msg","你已绑定代理~");
					retMap.put("uid",pppUser.getUid()+"");
					retMap.put("name",pppUser.getNickname());
					return JsonUtil.toJson(retMap);
				}else{
					retMap.put("code", "1");
					retMap.put("msg","未绑定代理");
					return JsonUtil.toJson(retMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("系统错误，请稍候再试！-----" + uid);
		}
		
		retMap.put("code", "2");
		retMap.put("msg","查询用户有误~");
		return JsonUtil.toJson(retMap);
		
		
	}
	
	
	
	
}
